﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace JuCloudy.Framework.Process
{
    public class vProcessManagement: INotifyCollectionChanged
    {
        private UIElement _mainStructure
        {
            get { return Application.Current.RootVisual; }
        }

        private Dictionary<int, VirtualProcessBase> _vprocess = new Dictionary<int, VirtualProcessBase>();
        
        public int InvokeProcess(VirtualProcessBase Process)
        {
            int no = _vprocess.Count;

            while (_vprocess.ContainsKey(no))
            {
                no++;
            }


            Thread t = new Thread(() =>
            {
                Process.vInitialization.Invoke();
                //Application.Current.RootVisual.Dispatcher.BeginInvoke(Process.vInitialization);
            });
            t.Start();
            while (t.IsAlive)
                continue;
            _vprocess.Add(no, Process);
            if (CollectionChanged != null)
                CollectionChanged.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, Process, no));
            return no;
        }

        public void Sleep(int vId)
        {
            var process = _vprocess[vId];
            process.Sleep();
        }

        public void Wake(int vId)
        {
            var process = _vprocess[vId];
            process.Wake();
        }

        public void Close(int vId)
        {
            var process = _vprocess[vId];
            /*var res = process.vClose.BeginInvoke(null, null);
            while (res.IsCompleted)
            {
                _vprocess.Remove(vId);
                if (CollectionChanged != null)
                    CollectionChanged.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, process, vId));
            }*/

            Thread t = new Thread(() =>
            {
                process.vClose.Invoke();
                //Application.Current.RootVisual.Dispatcher.BeginInvoke(process.vClose);
            });
            t.Start();
            while (t.IsAlive)
                continue;
            _vprocess.Remove(vId);
            if (CollectionChanged != null)
                CollectionChanged.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, process, vId));
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}
